package juc;
/*
    一、用于解决多线程安全问题的方式

    synchronized:隐式锁
    1.同步代码块
    2.同步方法

    jdk1.5后
    3.同步锁Lock
    是一个显示锁，需要通过lock()方法上锁，必须通过unlock()方法释放锁

*/

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "1号").start();
        new Thread(ticket, "2号").start();
        new Thread(ticket, "3号").start();
    }
}
class Ticket implements Runnable {

    private int ticket = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (ticket > 0)
                    System.out.println(Thread.currentThread().getName() + "完成售票，余票为：" + --ticket);
                else {
                    System.out.println("票没了");
                    break;
                }
            } finally {
                lock.unlock();
            }

        }
    }
}